package com.example.pcl.handler;

import com.example.pcl.constant.MessageConstants;
import com.example.pcl.constant.StatusCodeConstants;
import com.example.pcl.exception.BaseException;
import com.example.pcl.result.Result;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.sql.SQLException;
import java.sql.SQLIntegrityConstraintViolationException;

/**
 * 全局异常处理器，处理项目中抛出的业务异常
 */
@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    /**
     * 捕获业务异常
     *
     * @param ex
     * @return
     */
    @ExceptionHandler
    public Result<String> exceptionHandler(BaseException ex) {
        log.error("异常信息：{}", ex.getMessage());
        return Result.error(StatusCodeConstants.INTERNAL_SERVER_ERROR, ex.getMessage());
    }

    /**
     * 捕获sql异常
     *
     * @param ex
     * @return
     */
    @ExceptionHandler
    public Result<String> exceptionHandler(SQLIntegrityConstraintViolationException ex) {
        String message = ex.getMessage();
        log.error("异常信息：{}", message);
        return Result.error(StatusCodeConstants.INTERNAL_SERVER_ERROR, message.contains("Duplicate entry") ?
                message.split(" ")[2] + MessageConstants.ACCOUNT_EXIST : message.contains("a foreign key constraint fails") ? "删除的信息存在外键约束，请检查后再删除哦" : MessageConstants.UNKNOWN_ERROR);
    }

    // 捕获验证异常
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseEntity<Result<String>> handleValidationException(@NotNull MethodArgumentNotValidException ex) {
        BindingResult result = ex.getBindingResult();
        StringBuilder errorMessage = new StringBuilder();

        // 遍历所有字段的错误，构建错误信息
        for (FieldError fieldError : result.getFieldErrors()) {
            errorMessage.append(fieldError.getField())
                    .append(": ")
                    .append(fieldError.getDefaultMessage())
                    .append("; ");
        }
        return new ResponseEntity<>(Result.error(StatusCodeConstants.BAD_REQUEST, errorMessage.toString()), HttpStatus.BAD_REQUEST);
    }

    // 处理 SQL 错误（例如外键约束错误）
    @ExceptionHandler(SQLException.class)
    public ResponseEntity<Result<?>> handleSQLException(@NotNull SQLException ex) {
        return new ResponseEntity<>(Result.error(StatusCodeConstants.BAD_REQUEST, "数据库错误: " + ex.getMessage()), HttpStatus.BAD_REQUEST);
    }
}
